package com.whmskj.xjlhbc.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.domain.Bcsc15sctz;
import com.whmskj.xjlhbc.domain.EquipmentCounterStatements;
import com.whmskj.xjlhbc.mapper.Bcsc15sctzMapper;
import com.whmskj.xjlhbc.mapper.HomeMapper;
import com.whmskj.xjlhbc.mobile.GetStartDate;
import com.whmskj.xjlhbc.service.IHomeService;
import com.whmskj.xjlhbc.vo.HomeDataChartVo;
import com.whmskj.xjlhbc.vo.HomeDataVo;
import com.whmskj.xjlhbc.vo.HomeRealinfoDataVo;
import com.whmskj.xjlhbc.vo.HomeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HomeServiceImpl implements IHomeService {

    @Autowired
    private HomeMapper homeMapper;

    @Autowired
    private Bcsc15sctzMapper bcsc15sctzMapper;

    @Override
    public HomeVo query() {
        String month = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        HomeVo homeVo = new HomeVo();
        HomeVo.Top top = homeVo.getTop();
        HomeVo.TopBoard by = homeMapper.sjtj(month);
        month = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
        HomeVo.TopBoard sy = homeMapper.sjtj(month);
        top.setBy(by);
        top.setSy(sy);

        setCldbChart(homeVo);
        setClqxChart(homeVo);
        setCqxx(homeVo);

        List<Integer> sbzt = homeVo.getSbzt();
        sbzt.add(homeMapper.selectSbzt("运行"));
        sbzt.add(homeMapper.selectSbzt("临停"));
        sbzt.add(homeMapper.selectSbzt("待机"));
        sbzt.add(homeMapper.selectSbzt("离线"));
        homeVo.setGzlx(homeMapper.selectGzlx());
        homeVo.setStop(homeMapper.selectStop());
        setClqs(homeVo);
        setNhqs(homeVo);
        return homeVo;
    }


    @Override
    public HomeDataVo data() {
        String month = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        HomeDataVo.HomeDataParamVo by = homeMapper.selectHomeData(month);
        month = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
        HomeDataVo.HomeDataParamVo sy = homeMapper.selectHomeData(month);
        HomeDataVo result = new HomeDataVo();
        result.setBy(by);
        result.setSy(sy);
        return result;
    }

    @Override
    public Object realInfoData() {
        String day = GetStartDate.getDayStartDate();
        HomeRealinfoDataVo result = homeMapper.realInfoData(day);
        HomeRealinfoDataVo result1 = homeMapper.realInfoDataZzcj(day);//整经车间
        HomeRealinfoDataVo result2 = homeMapper.realInfoDataZlcj(day);//整理车间
        Map<String, Object> map = new HashMap<>();
        map.put("zb", result);
        map.put("zz", result1);
        map.put("zl", result2);
        return map;
    }

    @Override
    public List<Map<String, Object>> cldb() {
        String now = LocalDate.now().toString();
        return homeMapper.cldb(now);
    }

    @Override
    public HomeDataChartVo cldbWeek() {
        LocalDate end = LocalDate.now();
        LocalDate start = LocalDate.now().minusDays(6);
        List<String> dates = getDate(start, end);
        List<String> legends = Arrays.asList("甲班", "乙班");
        List<List<Double>> value = new ArrayList<>();
        legends.forEach(d->{
            List<Double> doubleList = new ArrayList<>();
            dates.forEach(date->{
                List<Map<String, Object>> list = homeMapper.cldb(date);
                Optional<Map<String, Object>> optional = list.stream().filter(filter -> d.equals(filter.get("classes"))).findFirst();
                doubleList.add(optional.map(map -> NumberUtil.parseDouble(String.valueOf(map.get("cl")), 0.0)).orElse(0.0));
            });
            value.add(doubleList);
        });
        HomeDataChartVo result = new HomeDataChartVo();
        result.setXData(dates);
        result.setLegends(legends);
        result.setValue(value);
        return result;
    }

    @Override
    public HomeDataChartVo clMonth() {
        LocalDate end = LocalDate.now();
        LocalDate start = LocalDate.now().minusDays(30);
        List<String> dates = getDate(start, end);
        List<List<Double>> value = new ArrayList<>();
        List<Double> doubleList = new ArrayList<>();
        dates.forEach(date->{
            List<Map<String, Object>> list = homeMapper.cldb(date);
            double sum = list.stream().mapToDouble(map -> NumberUtil.parseDouble(String.valueOf(map.get("cl")), 0.0)).sum();
            doubleList.add(NumberUtil.parseDouble(String.format("%.2f",sum)));
        });
        value.add(doubleList);
        HomeDataChartVo result = new HomeDataChartVo();
        result.setXData(dates);
        result.setValue(value);
        return result;
    }

    @Override
    public Object jtzt(String workshop) {
        Map<String, Object> map = new HashMap<>();
        List<EquipmentCounterStatements> list = homeMapper.selectJtzt(workshop);
        long count1 = list.stream().filter(f -> f.getStatus().equals("运行")).count();
        long count2 = list.stream().filter(f -> f.getStatus().equals("临停")).count();
        long count3 = list.stream().filter(f -> f.getStatus().equals("待机")).count();
        long count4 = list.stream().filter(f -> f.getStatus().contains("维保")).count();
        long count5 = list.stream().filter(f -> f.getStatus().equals("离线")).count();
        map.put("yx", count1);
        map.put("lt", count2);
        map.put("dj", count3);
        map.put("wb", count4);
        map.put("lx", count5);
        return map;
    }

    @Override
    public Object jtztListGroupByName(String status, String workshop) {
        List<EquipmentCounterStatements> list = homeMapper.selectJtzt(workshop);
        if(StringUtils.hasText(status)){
            list = list.stream().filter(f -> f.getStatus().equals(status)).collect(Collectors.toList());
        }
        List<String> names = list.stream().map(EquipmentCounterStatements::getDeviceName).distinct().collect(Collectors.toList());
        List<EquipmentCounterStatements> finalList = list;
        return names.stream().map(name->{
            Map<String, Object> map = new HashMap<>();
            map.put("name", name);
            map.put("jtList", finalList.stream().filter(f -> f.getDeviceName().equals(name)).collect(Collectors.toList()));
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    public Object getHomeInfo() {
        String monthStartDate = GetStartDate.getMonthStartDate();
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> cjInfoMap = new HashMap<>();
        Map<String, Object> orderInfoMap = homeMapper.selectOrderInfo(monthStartDate);
        Map<String, Object> ckInfoMap = new HashMap<>();
        int year = DateUtil.date().year();
        int month = GetStartDate.getMonthValue();
        Map<String, Object> map = Optional.ofNullable(homeMapper.selectClWcqk(year, month)).orElseGet(HashMap::new);//产量完成情况
        Map<String, Object> clMap = new HashMap<>();
        Double v = NumberUtil.parseDouble(map.get("zjjhcl").toString(), 0.0);
        Double v1 = NumberUtil.parseDouble(map.get("zjwccl").toString(), 0.0);
        clMap.put("jh", v);
        clMap.put("wc", v1);
        clMap.put("bl", String.format("%.1f",v1/v * 100));
        cjInfoMap.put("zj", clMap);
        clMap = new HashMap<>();
        v = NumberUtil.parseDouble(map.get("jsjhcl").toString(), 0.0);
        v1 = NumberUtil.parseDouble(map.get("jswccl").toString(), 0.0);
        clMap.put("jh", v);
        clMap.put("wc", v1);
        clMap.put("bl", String.format("%.1f",v>0 ? v1/v * 100 : 0));
        cjInfoMap.put("js", clMap);
        clMap = new HashMap<>();
        v = NumberUtil.parseDouble(map.get("zbsjjhcl").toString(), 0.0);
        v1 = NumberUtil.parseDouble(map.get("zbsjwccl").toString(), 0.0);
        clMap.put("jh", v);
        clMap.put("wc", v1);
        clMap.put("bl", String.format("%.1f",v>0 ? v1/v * 100 : 0));
        cjInfoMap.put("zb", clMap);
        clMap = new HashMap<>();
        v = NumberUtil.parseDouble(String.valueOf(map.get("zljhcl")), 0.0);
        v1 = NumberUtil.parseDouble(String.valueOf(map.get("zlwccl")), 0.0);
        clMap.put("jh", v);
        clMap.put("wc", v1);
        clMap.put("bl", String.format("%.1f",v>0 ? v1/v * 100 : 0));
        cjInfoMap.put("zl", clMap);

        Map<String, Object> yskcMap = homeMapper.selectYsKc();
        Map<String, Object> cpkcMap = homeMapper.selectCpKc();

        LambdaQueryWrapper<Bcsc15sctz> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Bcsc15sctz::getReleaseTime).last("limit 1");
        Bcsc15sctz bcsc15sctz = bcsc15sctzMapper.selectOne(wrapper);
        ckInfoMap.put("ys", yskcMap);
        ckInfoMap.put("cp", cpkcMap);
        resultMap.put("realInfo", realInfoData());
        resultMap.put("cjInfo", cjInfoMap);
        resultMap.put("orderInfo", orderInfoMap);
        resultMap.put("ckInfo", ckInfoMap);
        resultMap.put("tzInfo", bcsc15sctz);
        return resultMap;
    }

    private List<String> getDate(LocalDate start,LocalDate end){
        List<String> dates = new ArrayList<>();
        while(!start.isAfter(end)){
            dates.add(start.toString());
            start = start.plusDays(1);
        }
        return dates;
    }

    private void setCldbChart(HomeVo homeVo){
        List<String> data = Arrays.asList("甲班", "乙班");
        List<String> xAxisData = getDate();
        List<List<Double>> value = new ArrayList<>();
        HomeVo.Chart cldbChart = homeVo.getCldbChart();
        cldbChart.setXAxisData(xAxisData);
        cldbChart.setData(data);
        data.forEach(classes->{
            List<Double> doubleList = new ArrayList<>();
            xAxisData.forEach(date-> doubleList.add(homeMapper.select(classes, date)));
            value.add(doubleList);
        });
        cldbChart.setValue(value);
    }

    private void setClqxChart(HomeVo homeVo){
        List<String> data = Arrays.asList("整经", "浆纱");
        List<String> xAxisData = getDate();
        List<List<Double>> value = new ArrayList<>();
        HomeVo.Chart clqxChart = homeVo.getClqxChart();
        clqxChart.setXAxisData(xAxisData);
        clqxChart.setData(data);

        List<Double> doubleList = new ArrayList<>();
        List<Double> doubleList1 = new ArrayList<>();
        xAxisData.forEach(date->{
            doubleList.add(homeMapper.selectZj(date));
            doubleList1.add(homeMapper.selectJs(date));
        });
        value.add(doubleList);
        value.add(doubleList1);
        clqxChart.setValue(value);
    }

    private void setCqxx(HomeVo homeVo){
        List<HomeVo.Cqxx> cqxxList = homeVo.getCqxx();
        String workshop = "织布车间";
        HomeVo.Cqxx cqxx = new HomeVo.Cqxx();
        cqxx.setTotal(homeMapper.selectPersonnelTotal(workshop));
        cqxx.setCq(homeMapper.selectPersonnel(workshop,"出勤"));
        cqxx.setQq(homeMapper.selectPersonnel(workshop,"缺勤"));
        cqxx.setXx(homeMapper.selectPersonnel(workshop,"休息"));
        cqxx.setLz(homeMapper.selectPersonnel(workshop,"离职"));
        cqxx.setList(homeMapper.selectPersonnelList(workshop));

        cqxxList.add(cqxx);
        workshop = "准整车间";
        cqxx = new HomeVo.Cqxx();
        cqxx.setTotal(homeMapper.selectPersonnelTotal(workshop));
        cqxx.setCq(homeMapper.selectPersonnel(workshop,"出勤"));
        cqxx.setQq(homeMapper.selectPersonnel(workshop,"缺勤"));
        cqxx.setXx(homeMapper.selectPersonnel(workshop,"休息"));
        cqxx.setLz(homeMapper.selectPersonnel(workshop,"离职"));
        cqxx.setList(homeMapper.selectPersonnelList(workshop));
        cqxxList.add(cqxx);
    }

    private void setClqs(HomeVo homeVo){
        HomeVo.BottomChart clqsChart = homeVo.getClqsChart();
        List<String> data = getMonth();
        List<Double> value = new ArrayList<>();
        data.forEach(d->{
            value.add(homeMapper.seletCl(d));
        });
        clqsChart.getData().addAll(data);
        clqsChart.getValue().addAll(value);
    }

    private void setNhqs(HomeVo homeVo){
        List<Double> value = new ArrayList<>();
        List<String> data = getMonth();
        for(int i=0;i<data.size();i++){
            value.add(0.0);
        }
        HomeVo.BottomChart nhqsChart = homeVo.getNhqsChart();
        nhqsChart.getData().addAll(data);
        nhqsChart.getValue().addAll(value);
    }

    private List<String> getDate(){
        LocalDate end = LocalDate.now();
        LocalDate start = end.minusDays(6);
        List<String> dates = new ArrayList<>();
        while(!start.isAfter(end)){
            dates.add(start.toString());
            start = start.plusDays(1);
        }
        return dates;
    }

    private List<String> getMonth(){
        LocalDate end = LocalDate.now();
        LocalDate start = end.minusDays(30);
        List<String> dates = new ArrayList<>();
        while(!start.isAfter(end)){
            dates.add(start.toString());
            start = start.plusDays(1);
        }
        return dates;
    }
}
